package com.konsung.ksdc.manager.community;

import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.stmt.QueryBuilder;
import com.konsung.ksdc.R;
import com.konsung.ksdc.bean.MqttMsgNotice;
import com.konsung.ksdc.bean.netbean.GroupNetBean;
import com.konsung.ksdc.bean.netbean.RegisterUserNetBean;
import com.konsung.ksdc.common.database.DatabaseHelper;
import com.konsung.ksdc.common.mqtt.MqttMsgUtils;
import com.konsung.ksdc.common.mqtt.MqttNoticeConstant;
import com.konsung.ksdc.common.network.RequestUtils;
import com.konsung.ksdc.common.utils.BroadCastActions;
import com.konsung.ksdc.common.utils.DateUtils;
import com.konsung.ksdc.common.utils.StringUtils;
import com.konsung.ksdc.common.utils.ToastUtils;
import com.konsung.ksdc.config.MyApplication;
import com.konsung.ksdc.config.NetConfig;
import com.squareup.picasso.Picasso;

import java.sql.SQLException;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 消息提醒界面
 * Created by andy on 2017/4/24.
 */
public class NoticeFragment extends Fragment {
    @Bind(R.id.ll_msg_notice)
    LinearLayout llMsgNotice;

    // 最后一次发送/接收时间标识
//    private long lastTimeFlag = new Date().getTime();
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
        View view = inflater.inflate(R.layout.fragment_msg_history, null);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        rendderNoticeView();
        registerReceiver();
    }

    /**
     * 注册网络断开广播
     */
    private void registerReceiver() {
        IntentFilter intent = new IntentFilter();
        intent.addAction(BroadCastActions.ACTION_MESSAGE_RECEIVED);
        intent.addAction(BroadCastActions.ACTION_DELETE_CONTACT);
        intent.addAction(BroadCastActions.ACTION_REQUEST_RECEIVED);
        intent.addAction(BroadCastActions.ACTION_REQUEST_PASSED);
        intent.addAction(BroadCastActions.ACTION_RECEIVED_WIKI);
        intent.addAction(BroadCastActions.ACTION_DELETE_GROUP_ME); //收到移除自己的广播，消息界面移除
//        intent.addAction(BroadCastActions.ACTION_REQUEST_GROUP_RECEIVED);
        getActivity().registerReceiver(receiver, intent);
    }

    @Override
    public void onResume() {
        super.onResume();
        rendderNoticeView();
    }

    /**
     * 广播接收者
     */
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (BroadCastActions.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
                rendderNoticeView();
            }
            if (BroadCastActions.ACTION_DELETE_CONTACT.equals(intent.getAction())) {
                rendderNoticeView();
            }
            if (BroadCastActions.ACTION_MESSAGE_PUBLISHED.equals(intent.getAction())) {
                rendderNoticeView();
            }
            if (BroadCastActions.ACTION_REQUEST_PASSED.equals(intent.getAction())) {
                rendderNoticeView();
            }
            if (BroadCastActions.ACTION_REQUEST_RECEIVED.equals(intent.getAction())) {
                rendderNoticeView();
            }
            if (BroadCastActions.ACTION_RECEIVED_WIKI.equals(intent.getAction())) {
                rendderNoticeView();
            }
            if (BroadCastActions.ACTION_DELETE_GROUP_ME.equals(intent.getAction())) {
                rendderNoticeView();
            }
        }
    };

    /**
     * 渲染消息提醒组件
     */
    private void rendderNoticeView() {
        //避免空指针
        if (llMsgNotice != null && llMsgNotice.getChildCount() > 0) {

            llMsgNotice.removeAllViews();
        }
        RuntimeExceptionDao dao = DatabaseHelper.getHelper(getActivity())
                .getRuntimeExceptionDao(MqttMsgNotice.class);
        if (NetConfig.currentUser == null || NetConfig.currentUser.getUserId() == null) {
            //避免数据库查询为空，出现异常
            return;
        }
        List<MqttMsgNotice> notices = null;
        try {
            QueryBuilder qb = dao.queryBuilder();
            qb.where().eq("ownerUserId", NetConfig.currentUser.getUserId());
            notices = qb.orderBy("timestamp", true).query();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        if (notices == null) {
            return;
        }

        for (MqttMsgNotice notice : notices) {
            //拦截注册前的消息
            if (DateUtils.compareMsgTime(notice.getTimestamp())) {
                continue;
            }
            if (MqttNoticeConstant.NOTICE_TYPE_REQUEST == notice
                    .getNoticeType()) {
                // 添加好友验证信息消息提醒
                View item = getContactRequestView(notice);
                if (item != null) {
                    llMsgNotice.addView(item, 0);
                }
                continue;
            }
//            添加群消息验证信息提心
//            if (MqttNoticeConstant.NOTICE_TYPE_GROUP == notice
//                    .getNoticeType()) {
//                // 添加群消息提醒
//
//                View item = getGroupNoticeView(notice);
//                if (item != null) {
//                    llMsgNotice.addView(item, 0);
//                }
//                continue;
//            }
            if (MqttMsgUtils.MSG_TARGET_TYPE_PERSONAL.equals(notice
                    .getTargetType())) {
                // 添加个人消息提醒显示
                View item = getContactNoticeView(notice);
                if (item != null) {
                    llMsgNotice.addView(item, 0);
                }
            } else {
                View item = getGroupNoticeView(notice);
                if (item != null) {
                    llMsgNotice.addView(item, 0);
                }
            }
        }
    }

    /**
     * 添加好友消息提醒
     * @param notice MqttMsgNotice
     * @return view
     */
    private View getContactNoticeView(final MqttMsgNotice notice) {
        // 清除已有项目
        clearContactNotice(notice);

        final View noticeView = LayoutInflater.from(getActivity())
                .inflate(R.layout.view_msg_history, null);

        // 从顶层容器中取得好友对象
        final RegisterUserNetBean user = findUserByUserId(notice.getTopicName());
        if (user == null) {
            return null;
        }

        ImageView imgNotice = (ImageView) noticeView
                .findViewById(R.id.img_notice_state);
        ImageView imgContactPic = (ImageView) noticeView
                .findViewById(R.id.img_contact_pic);
        TextView txtNoticeName = (TextView) noticeView
                .findViewById(R.id.txt_notice_name);
        TextView txtNoticeContent = (TextView) noticeView
                .findViewById(R.id.txt_notice_content);
        TextView txtNoticeTime = (TextView) noticeView
                .findViewById(R.id.txt_notice_time);
        String picPath = StringUtils.appendPicPath(user.getUserPic());

        Picasso.with(getActivity())
                .load(picPath)
                .placeholder(R.drawable.pic_talkbox_sel)
                .error(R.drawable.pic_talkbox_sel)
                .into(imgContactPic);

        if (notice.getIsRead().equals("N")) {
            imgNotice.setImageResource(R.drawable.pic_news_touxiangkuang);
        }

        txtNoticeName.setText(StringUtils.stringOmitRear(user.getNickName()));
        txtNoticeContent.setText(notice.getNoticeMsg());
        txtNoticeTime.setText(DateUtils.compareTime(notice.getTimestamp()));
        noticeView.setTag(notice.getTopicName());

        if (MqttNoticeConstant.NOTICE_TYPE_WIKI == notice.getNoticeType()) {
            noticeView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    openWikiChat();
                }
            });
        } else {
            noticeView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (!RequestUtils.isNetworkConnected(getActivity())) {
                        ToastUtils.toastContent(getActivity(), getString(R.string.chat_unconnect));
                        return;
                    }
                    openChart(user);
                }
            });
        }

        return noticeView;
    }

    /**
     * 获取好友申请提醒视图
     * @param notice MqttMsgNotice
     * @return view
     */
    private View getContactRequestView(final MqttMsgNotice notice) {
        // 清除已有项目
        clearContactNotice(notice);

        final View noticeView = LayoutInflater.from(getActivity())
                .inflate(R.layout.view_msg_history, null);

        if (StringUtils.isEmpty(notice.getNoticeMsg())) {
            return null;
        }

        // 从顶层容器中取得好友对象
        Gson gson = new Gson();
        final RegisterUserNetBean user = gson
                .fromJson(notice.getNoticeMsg(), RegisterUserNetBean.class);
        if (user == null) {
            return null;
        }

        ImageView ivNotice = (ImageView) noticeView
                .findViewById(R.id.img_notice_state);
        ImageView ivContactPic = (ImageView) noticeView
                .findViewById(R.id.img_contact_pic);
        TextView tvNoticeName = (TextView) noticeView
                .findViewById(R.id.txt_notice_name);
        TextView tvNoticeContent = (TextView) noticeView
                .findViewById(R.id.txt_notice_content);
        TextView tvNoticeTime = (TextView) noticeView
                .findViewById(R.id.txt_notice_time);
        String picPath = StringUtils.appendPicPath(user.getUserPic());

        Picasso.with(getActivity())
                .load(picPath)
                .placeholder(R.drawable.pic_talkbox_sel)
                .error(R.drawable.pic_talkbox_sel)
                .into(ivContactPic);

        if (notice.getIsRead().equals("N")) {
            ivNotice.setImageResource(R.drawable.pic_news_touxiangkuang);
        }

        tvNoticeName.setText(StringUtils.stringOmitRear(user.getNickName()));
        tvNoticeContent.setText(getString(R.string
                .contact_request));
        tvNoticeTime.setText(DateUtils.compareTime(notice.getTimestamp()));
        noticeView.setTag(notice.getTopicName());

        noticeView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), ContactRequestActivity.class);
                startActivity(intent);
            }
        });

        return noticeView;
    }

    /**
     * 添加群组消息提醒
     * @param notice MqttMsgNotice
     * @return view
     */
    private View getGroupNoticeView(final MqttMsgNotice notice) {
        // 清除已有项目
        clearContactNotice(notice);
        final View noticeView = LayoutInflater.from(getActivity())
                .inflate(R.layout.view_msg_history, null);
        GroupNetBean group = findGroupByGroupId(notice.getTopicName());
        if (group == null) {
            return null;
        }

        final String groupName = group.getGroupName();
        ImageView imgNotice = (ImageView) noticeView
                .findViewById(R.id.img_notice_state);
        ImageView imgGroupPic = (ImageView) noticeView
                .findViewById(R.id.img_contact_pic);
        TextView txtNoticeName = (TextView) noticeView
                .findViewById(R.id.txt_notice_name);
        TextView txtNoticeContent = (TextView) noticeView
                .findViewById(R.id.txt_notice_content);
        TextView txtNoticeTime = (TextView) noticeView
                .findViewById(R.id.txt_notice_time);

        if (notice.getIsRead().equals("N")) {
            imgNotice.setImageResource(R.drawable.pic_news_touxiangkuang);
        }
        //显示头像
        Glide.with(MyApplication.getContext()).load(StringUtils.appendPicPath(group.getGroupPic()
        )).error(R.drawable.pic_head_defult).crossFade(1000).
                into(imgGroupPic);

        // 群组名
        txtNoticeName.setText(StringUtils.stringOmitRear(groupName));
        // 提醒内容
        txtNoticeContent.setText(notice.getNoticeMsg());

        // 消息时间
        txtNoticeTime.setText(DateUtils.compareTime(notice.getTimestamp()));

        noticeView.setTag(notice.getTopicName());

        noticeView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(getActivity(), GroupChatActivity.class);
                intent.putExtra("topicName", notice.getTopicName());
                intent.putExtra("groupName", groupName);
                getActivity().startActivity(intent);
            }
        });

        return noticeView;
    }

    /**
     * 如果消息项已经存在则移除之
     * @param notice MqttMsgNotice
     */
    private void clearContactNotice(MqttMsgNotice notice) {
        clearNoticeView(notice.getTopicName());
    }

    /**
     * 移除消息提醒视图
     * @param tagId tagId
     */
    private void clearNoticeView(String tagId) {
        View msgItem = llMsgNotice.findViewWithTag(tagId);
        if (msgItem != null) {
            llMsgNotice.removeView(msgItem);
        }
    }

    /**
     * 通过群组ID查询群组
     * @param topicName 群组id
     * @return 群组Bean
     */
    private GroupNetBean findGroupByGroupId(String topicName) {

        Dao dao = null;
        try {
            dao = DatabaseHelper
                    .getHelper(getActivity())
                    .getDao(GroupNetBean.class);
            QueryBuilder qb = dao.queryBuilder();
            qb.where().eq("groupId", topicName).and().eq("ownerId",
                    NetConfig.currentUser.getUserId());
            List<GroupNetBean> groups = dao.query(qb.prepare());
            if (null != groups && groups.size() > 0) {
                return groups.get(0);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 从本地数据库取好友数据
     * @param userId 用户id
     * @return 注册用户信息bean
     */
    private RegisterUserNetBean findUserByUserId(String userId) {
        RuntimeExceptionDao dao = DatabaseHelper.getHelper(getActivity())
                .getRuntimeExceptionDao(RegisterUserNetBean.class);

        List<RegisterUserNetBean> users = dao.queryForEq("userId", userId);
        if (users != null && !users.isEmpty()) {
            return users.get(0);
        }

        return null;
    }

    /**
     * 打开聊天界面
     * @param user 用户bean
     */
    public void openChart(RegisterUserNetBean user) {
        String contactUserId = user.getUserId();
        String contactUserName = user.getUserName();
        String nickName = user.getNickName();
        String picPath = user.getUserPic();
        Intent intent = new Intent(getActivity(), ChatActivity.class);
        intent.putExtra("userId", contactUserId);
        intent.putExtra("topicName", contactUserName);
        intent.putExtra("nickName", nickName);
        intent.putExtra("picPath", picPath);
        Gson gson = new Gson();
        intent.putExtra("data", gson.toJson(user));
        startActivity(intent);
    }

    /**
     * 打开康尚健康百科消息页
     */
    private void openWikiChat() {
        Intent intent = new Intent(getActivity(), KonsungWikiActivity.class);
        startActivity(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(receiver);
    }
}
